package com.winning.pmph.ctrl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.winning.pmph.entity.*;
import com.winning.pmph.service.*;
import com.winning.pmph.utils.*;
import com.winning.pmph.vo.CascaderOption;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Api(value = "考试用书")
@RestController
@RequestMapping("/pmph/action/examBook")
public class ExamBookCtrl {
    @Resource
    private ExamBookService examBookService;
    @Resource
    private ExamBookCatalogItemService examBookCatalogItemService;
    @Resource
    private ExamBookCatalogItemContentService examBookCatalogItemContentService;
    @Resource
    private ExamBookArticleService examBookArticleService;
    @Resource
    private ExamKnowledgeService examKnowledgeService;
    @Resource
    private BookCatalogItemService bookCatalogItemService;


    @ApiOperation(value = "importExamBooks", notes = "图书导入接口")
    @PostMapping("importExamBooks")
    public void importExamBooks(MultipartFile file, HttpServletRequest request) {
        String header = request.getHeader("user-agent");
        String userName = PMPHAppUtil.getCurrentUserEnName();
        String path = ApplicationContextUtil.BASE_DOWN_FORDER + "image/examBook/";
        String name = UploadFileUtil.uploadFile(file, path, false);
        ExamBook examBook = new ExamBook();
        examBook.setId("1502219859513278465");
        examBook.setStatus(Const.IMPORT_STATUS_IMPORTING);
        examBook.setPath(path + name);
        examBook.setName(StringUtils.removeEnd(name, ".zip"));
        examBook.setAdaptMajors("妇产科学（中级）");
        examBook.setMajorsCode("300");
        examBook.setCreatedBy(userName);
        examBook.setUpdatedBy(userName);
        examBookService.save(examBook);
        ExecutorServiceFactory.getInstance().submit(() -> {
            try {
                examBookService.importBook(examBook, header, userName);
            } catch (Exception exception) {
                examBook.setId(examBook.getId());
                examBook.setStatus(Const.IMPORT_STATUS_FAILURE);
                examBook.setFailureReason(exception.getMessage());
                throw new RuntimeException("考试指导用书导入失败:" + exception);
            } finally {
                examBookService.saveOrUpdate(examBook);
            }
        });
    }

    @ApiOperation(value = "selectGuideBookList", notes = "指导用书查询接口")
    @GetMapping("selectGuideBookList")
    public Page<ExamBook> selectGuideBookList(ExamBook guideBook) {
        LambdaQueryWrapper<ExamBook> query = Wrappers.lambdaQuery(ExamBook.class)
                .like(StringUtils.isNotBlank(guideBook.getName()), ExamBook::getName, guideBook.getName())
                .eq(StringUtils.isNotBlank(guideBook.getIsbn()), ExamBook::getIsbn, guideBook.getIsbn())
                .like(StringUtils.isNotBlank(guideBook.getAdaptMajors()), ExamBook::getAdaptMajors, guideBook.getAdaptMajors()).orderByDesc(ExamBook::getUpdatedTime);
        if (StringUtils.isNotBlank(guideBook.getImportTime())) {
            query = query.ge(ExamBook::getCreatedTime, guideBook.getImportTime().split(",")[0].trim())
                    .le(ExamBook::getCreatedTime, guideBook.getImportTime().split(",")[1].trim());
        }
        if (guideBook.getStartNum() >= 0 && guideBook.getEndNum() > 0) {
            query.ge(ExamBook::getNum, guideBook.getStartNum())
                    .le(ExamBook::getNum, guideBook.getEndNum());
        }
        return examBookService.getBaseMapper().selectPage(new Page<>(guideBook.getCurrentPage(), guideBook.getPageSize()), query);

    }

    @ApiOperation(value = "selectExamKnowledgeList", notes = "查看知识列表查询")
    @GetMapping("selectExamKnowledgeList")
    public Page<ExamKnowledge> selectExamKnowledgeList(ExamKnowledge examKnowledge) {
        LambdaQueryWrapper<ExamKnowledge> query = Wrappers.lambdaQuery(ExamKnowledge.class)
                .like(StringUtils.isNotBlank(examKnowledge.getName()), ExamKnowledge::getName, examKnowledge.getName())
                .eq(StringUtils.isNotBlank(examKnowledge.getOutlineDetailId()), ExamKnowledge::getOutlineDetailId, examKnowledge.getOutlineDetailId())
                .eq(ExamKnowledge::getExamBookId, examKnowledge.getExamBookId()).orderByAsc(ExamKnowledge::getBookCatalogItemId);
        if (StringUtils.isNotEmpty(examKnowledge.getCreatedTime())) {
            query = query.ge(ExamKnowledge::getCreatedTime, examKnowledge.getCreatedTime().split(",")[0].trim())
                    .le(ExamKnowledge::getCreatedTime, examKnowledge.getCreatedTime().split(",")[1].trim());
        }
        Page<ExamKnowledge> examKnowledgePage = examKnowledgeService.getBaseMapper().selectPage(new Page<>(examKnowledge.getCurrentPage(), examKnowledge.getPageSize()), query);

        return examKnowledgePage;
    }


    @ApiOperation(value = "selectExamBookArticle", notes = "查询指导用书详情")
    @GetMapping("selectExamBookArticle")
    public ExamBookArticle selectExamBookArticle(String bookArticleId) {
        return examBookArticleService.getById(bookArticleId);
    }

    @ApiOperation(value = "selectExamBookTree", notes = "查询树结构")
    @GetMapping("selectExamBookTree")
    public List<ExamBookCatalogItem> selectExamBookTree(String bookId) {
        List<ExamBookCatalogItem> catalogItemList = examBookCatalogItemService.getBaseMapper().selectList(Wrappers.lambdaQuery(ExamBookCatalogItem.class)
                .eq(ExamBookCatalogItem::getBookId, bookId));
        Map<String, ExamBookCatalogItem> id2item = catalogItemList.stream().collect(Collectors.toMap(ExamBookCatalogItem::getId, item -> item));
        for (ExamBookCatalogItem bookCatalogItem : catalogItemList) {
            if (StringUtils.isBlank(bookCatalogItem.getParentId())) {
                continue;
            } else {
                ExamBookCatalogItem parentNode = id2item.get(bookCatalogItem.getParentId());
                if (Objects.isNull(parentNode.getChildren())) {
                    parentNode.setChildren(Lists.newArrayList());
                }
                parentNode.getChildren().add(bookCatalogItem);
            }
        }
        // 查询一级
        List<ExamBookCatalogItem> oneLevelTag = catalogItemList.stream().filter(t -> StringUtils.isBlank(t.getParentId())).collect(Collectors.toList());
        return oneLevelTag;
    }

    @ApiOperation(value = "saveExamBook", notes = "保存指导用书")
    @PostMapping("saveExamBook")
    public void saveExamBook(String examBook) {
        ExamBook book = JSON.parseObject(examBook, ExamBook.class);
        examBookService.updateById(book);
    }

    @ApiOperation(value = "saveExamKnowledge", notes = "指导用书新增知识接口")
    @PostMapping("saveExamKnowledge")
    public void saveExamKnowledge(@RequestBody ExamKnowledge examKnowledge) {
        examKnowledgeService.saveExamKnowledge(examKnowledge);
    }

    @ApiOperation(value = "deleteExamBookById", notes = "根据id或批量删除指导用书")
    @PostMapping("deleteExamBookById")
    public void deleteExamBookById(String ids) {
        examBookService.removeByIds(Arrays.asList(ids.split(",")));
    }


    @ApiOperation(value = "deletedExamKnowledgeById", notes = "根据id或批量删除指导用书知识")
    @GetMapping("deletedExamKnowledgeById")
    public void deletedExamKnowledgeById(String ids, String examOutlineId, String examBookId) {
        examKnowledgeService.deletedExamKnowledgeById(ids, examOutlineId, examBookId);
    }


    @ApiOperation(value = "selectOutlineTree", notes = "根据id查询大纲")
    @GetMapping("selectOutlineTree")
    public List<CascaderOption> selectOutlineTree(String examOutlineId) {
        return examBookService.getTree(examOutlineId);
    }

    @ApiOperation(value = "selectExamKnowledgeById", notes = "查询指导用书知识ID查看详情")
    @GetMapping("selectExamKnowledgeById")
    public ExamKnowledge selectExamKnowledgeById(String id) {

        ExamKnowledge examKnowledge = examKnowledgeService.getById(id);
        String knowledgeText = examBookService.splitExamKnowledge(examKnowledge).getKnowledgeText();
        examKnowledge.setKnowledgeText(knowledgeText);
        return examKnowledge;
    }

    @ApiOperation(value = "selectExamBookIdByExamOutlineId", notes = "根据大纲ID查询关联图书ID")
    @GetMapping("selectExamBookIdByExamOutlineId")
    public ExamBook selectExamBookIdByExamOutlineId(String examOutlineId) {
        return examBookService.lambdaQuery().eq(ExamBook::getExamOutlineId, examOutlineId).one();
    }

    @ApiOperation(value = "selectBookCatalogItemById", notes = "根据BookCatalogItemId 查询")
    @GetMapping("selectBookCatalogItemById")
    public BookCatalogItem selectBookCatalogItemById(String id) {
        return bookCatalogItemService.getById(id);
    }

    @ApiOperation(value = "selectAllOutlineTree", notes = "查询所有大纲组装成树")
    @GetMapping("selectAllOutlineTree")
    public List<CascaderOption> selectAllOutlineTree() {
        return examBookService.selectAllOutlineTree();
    }
}
